package services

import (
	"time"

	"gitee.com/kun_liu/to-log/app/models"
	"gitee.com/kun_liu/to-log/pkg/database"
	"gorm.io/gorm"
)

// UserService 用户服务
type UserService struct {
	db *gorm.DB
}

// NewUserService 创建用户服务
func NewUserService() *UserService {
	return &UserService{
		db: database.GetDB(),
	}
}

// GetUsers 获取用户列表
func (s *UserService) GetUsers(page, pageSize int) ([]models.User, int64, error) {
	var users []models.User
	var total int64

	// 获取总数
	s.db.Model(&models.User{}).Count(&total)

	// 获取分页数据
	result := s.db.Order("created DESC").Limit(pageSize).Offset((page - 1) * pageSize).Find(&users)

	return users, total, result.Error
}

// GetUserByID 根据ID获取用户
func (s *UserService) GetUserByID(id uint) (models.User, error) {
	var user models.User
	result := s.db.First(&user, id)
	return user, result.Error
}

// GetUserByName 根据用户名获取用户
func (s *UserService) GetUserByName(name string) (models.User, error) {
	var user models.User
	result := s.db.Where("name = ?", name).First(&user)
	return user, result.Error
}

// GetUserByEmail 根据邮箱获取用户
func (s *UserService) GetUserByEmail(email string) (models.User, error) {
	var user models.User
	result := s.db.Where("mail = ?", email).First(&user)
	return user, result.Error
}

// CreateUser 创建用户
func (s *UserService) CreateUser(user *models.User) error {
	// 开始事务
	tx := s.db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 创建用户
	if err := tx.Create(user).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 提交事务
	return tx.Commit().Error
}

// UpdateUser 更新用户
func (s *UserService) UpdateUser(user *models.User) error {
	// 开始事务
	tx := s.db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 更新用户
	if err := tx.Save(user).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 提交事务
	return tx.Commit().Error
}

// DeleteUser 删除用户
func (s *UserService) DeleteUser(id uint) error {
	// 开始事务
	tx := s.db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 获取用户
	var user models.User
	if err := tx.First(&user, id).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 检查是否有关联的文章
	var postCount int64
	if err := tx.Model(&models.Post{}).Where("author_id = ?", id).Count(&postCount).Error; err != nil {
		tx.Rollback()
		return err
	}

	if postCount > 0 {
		tx.Rollback()
		return gorm.ErrForeignKeyViolated
	}

	// 检查是否有关联的评论
	var commentCount int64
	if err := tx.Model(&models.Comment{}).Where("author_id = ?", id).Count(&commentCount).Error; err != nil {
		tx.Rollback()
		return err
	}

	if commentCount > 0 {
		tx.Rollback()
		return gorm.ErrForeignKeyViolated
	}

	// 删除用户
	if err := tx.Delete(&user).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 提交事务
	return tx.Commit().Error
}

// Login 用户登录
func (s *UserService) Login(name, password string) (models.User, error) {
	var user models.User

	// 查询用户
	result := s.db.Where("name = ?", name).First(&user)
	if result.Error != nil {
		return user, result.Error
	}

	// 验证密码
	if !user.CheckPassword(password) {
		return user, gorm.ErrRecordNotFound
	}

	// 更新最后登录时间
	user.Activated = time.Now().Unix()
	s.db.Save(&user)

	return user, nil
}

// Register 用户注册
func (s *UserService) Register(user *models.User) error {
	// 开始事务
	tx := s.db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 检查用户名是否已存在
	var count int64
	if err := tx.Model(&models.User{}).Where("name = ?", user.Name).Count(&count).Error; err != nil {
		tx.Rollback()
		return err
	}

	if count > 0 {
		tx.Rollback()
		return gorm.ErrDuplicatedKey
	}

	// 检查邮箱是否已存在
	if err := tx.Model(&models.User{}).Where("mail = ?", user.Mail).Count(&count).Error; err != nil {
		tx.Rollback()
		return err
	}

	if count > 0 {
		tx.Rollback()
		return gorm.ErrDuplicatedKey
	}

	// 创建用户
	if err := tx.Create(user).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 提交事务
	return tx.Commit().Error
}
